const crypto = require('crypto');
const client = require('./mysql');
const axios = require('axios');

class data {
    // 封装SQL查询
    async query(sql, params) {
        // await client.startTransaction();
        var res = await client.query(sql, params);
        // await client.stopTransaction();
        return res;
    }

    id2Token(id) {
        var date = new Date();
        var str = parseInt(Math.random() * 1000) + id + 'guolingfeng' + date.getFullYear() + date.getMonth() + date.getDate() + date.getHours() + date.getMinutes() + date.getSeconds() + 'snake';
        return this.md5(str);
    }
    
    // 将一个字符串输出MD5哈希值
    md5(text) {
        return crypto.createHash('md5').update(text).digest('hex');
    }

    // 返回请求的Json
    setStatusJson(status, message) {
        var res = {
            status: status,
            message: message
        };
        return res;
    }

    // 判断一个值是否包含在数组中
    contains(arr, obj) {
        var i = arr.length;
        while (i--) {
            if (arr[i] == obj) {
                return true;
            }
        }
        return false;
    }

    // 判断是否为JSON
    isJson(str) {
        // var isjson = typeof (obj) == "object" && Object.prototype.toString.call(obj).toLowerCase() == "[object object]" && !obj.length;
        if (typeof str === 'string') {
            try {
                JSON.parse(str);
                return true;
            } catch (e) {
                console.log(e);
                return false;
            }
        } else {
            return false;
        }
    }

    // js时间戳转日期字符串
    getLocalTime(nS) {
        return new Date(parseInt(nS)).toLocaleString().replace(/年|月/g, '-').replace(/日/g, ' ');
    }

    // 输出当前前后的年月日
    GetDateStr(AddDayCount, date = null) {
        var dd;
        if (date == null) {
            dd = new Date();
        } else {
            dd = date;
        }
        dd.setDate(dd.getDate() + AddDayCount); // 获取AddDayCount天后的日期
        var y = dd.getFullYear();
        var m = dd.getMonth() + 1; // 获取当前月份的日期
        var d = dd.getDate();
        return y + '-' + m + '-' + d;
    }

    timeFormatter(da) {
        return da.getFullYear() + '-' + (da.getMonth() + 1) + '-' + da.getDate() + ' ' + da.getHours() + ':' + da.getMinutes() + ':' + da.getSeconds();
    }

    // 数字少于10时自动在前面填充一个0
    frontAdd0(num) {
        return num < 10 ? 0 + '' + num : num;
    }

    async Jsms_send(mobile, config) {
        var url = config.Jsms.smsSend;
        var authString = (await config.dynamic).Jmsm_AppKey + ':' + (await config.dynamic).Jmsm_AppSecret;
        var baseString = new Buffer(authString).toString('base64');
        var bodyData = {
            mobile: mobile.toString(),
            temp_id: '1'
        };
        var headers = {
            'Authorization': 'Basic ' + baseString,
            'Content-Type': 'application/json'
        };
        try {
            var resData = (await axios.post(url, JSON.stringify(bodyData), {
                headers: headers
            })).data;
        } catch (e) {
            console.log(e);
            return 'error';
        }
        return resData.msg_id;
    }

    async Jsms_verification(msgid, code, config) {
        var urlArray = config.Jsms.verification.split('{msg_id}');

        var url = urlArray[0] + msgid + urlArray[1];
        var authString = (await config.dynamic).Jmsm_AppKey + ':' + (await config.dynamic).Jmsm_AppSecret;
        var baseString = new Buffer(authString).toString('base64');
        var bodyData = {
            code: code
        };
        var headers = {
            'Authorization': 'Basic ' + baseString,
            'Content-Type': 'application/json'
        };
        try {
            var resData = (await axios.post(url, JSON.stringify(bodyData), {
                headers: headers
            })).data;
        } catch (e) {
            console.log(e);
            if (e.response.data.is_valid == false) {
                return false;
            }
            return 'error';
        }
        return resData.is_valid;
    }
}
exports.data = data;